export const listToTree = (data: any[], pid: string = "0", idKey: string = "id", pidKey: string = "pid", childrenKey: string = "children") => {
  data.forEach(item => {
    if (item[pidKey] === null) {
      item[pidKey] = "0";
    }
  });

  let cloneData = JSON.parse(JSON.stringify(data));

  const tree: any[] = [];
  cloneData.filter((father: any) => {
    let branchArr = cloneData.filter((child: any) => father[idKey] === child[pidKey]);
    let childs: any = [];
    for (let branchArrKey in branchArr) {
      childs[branchArrKey] = branchArr[branchArrKey];
    }
    childs.length > 0 ? father[childrenKey] = childs : undefined;

    if (String(father[pidKey]) === pid) {
      tree.push(father);
    }
  });

  return tree;
};

export const treeToList = (tree: any[], key: string = "id", title: string = "title", pid: string = "pid", children: string = "children") => {
  let list: any[] = [];
  tree.forEach(item => {
    let node = item;
    if (node[children] && node[children].length !== 0) {
      list.push({
        [key]: node[key],
        [title]: node[title],
        [pid]: node[pid],
      });
      if (node[children]) {
        toListDF(node[children], list, key, title, pid, children);
      }
    }

  });
  return list;
};

const toListDF = (childrenList: any, list: any[], key: string = "id", title: string = "title", pid: string = "pid", children: string = "children") => {
  childrenList.forEach((node: any) => {
    list.push({
      [key]: node[key],
      [title]: node[title],
      [pid]: node[pid],
    });
    if (node[children]) {
      toListDF(node[children], list, key, title, pid, children);
    }
  });
};


export const menuTreeToList = (tree: any[]) => {
  let list: any[] = [];
  tree.forEach(item => {
    let node = item;
    list.push(node);
    if (node.children && node.children.length !== 0) {
      list.push({
        id: node.id,
        name: node.name,
        pid: node.pid,
        path: node.path,
      });
      if (node.children) {
        menuToListDF(node.children, list, node.id);
      }
    }

  });
  return list;
};

const menuToListDF = (childrenList: any, list: any[], parentId: number) => {
  childrenList.forEach((node: any) => {
    list.push({
      id: node.id,
      name: node.name,
      pid: node.pid,
      path: node.path,
    });
    if (node.children) {
      menuToListDF(node.children, list, node.id);
    }
  });
};
